package com.example.cinema.service;

import com.example.cinema.dto.MovieDTO;
import com.example.cinema.model.Movie;
import com.example.cinema.repository.MovieRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MovieService {

    private final MovieRepository movieRepository;

    @Autowired
    public MovieService(MovieRepository movieRepository) {
        this.movieRepository = movieRepository;
    }

    // 添加电影
    public Movie addMovie(MovieDTO movieDTO) {
        Movie movie = new Movie(movieDTO.getTitle(), movieDTO.getDuration());
        return movieRepository.save(movie);
    }

    // 获取所有电影
    public List<MovieDTO> getAllMovies() {
        return movieRepository.findAll().stream()
                .map(movie -> new MovieDTO(movie.getId(), movie.getTitle(), movie.getDuration()))

                .collect(Collectors.toList());
    }

    // 根据ID获取电影
    public Movie getMovieById(Integer id) {
        return movieRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("电影不存在: " + id));
    }
}